//
//  CustomViewController.m
//  AmountBody
//
//  Created by Qiu Jishuai on 2017/12/30.
//  Copyright © 2017年 RCMTM. All rights reserved.
//

#import "CustomViewController.h"
#import "ReactiveObjC.h"
#import "Masonry.h"
#import <AmountBody-Swift.h>

#define kViewH (UIScreen.mainScreen.bounds.size.height - 49 - 64)

@interface CustomViewController()<UIScrollViewDelegate>
@property (nonatomic, strong) CustomNewsAmountViewController *amountVc;
@end

@implementation CustomViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = RGBColorAlpha(44, 44, 44, 1);

    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:_scrollView];
    if (@available(iOS 11.0, *)) {
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
//    _scrollView.alwaysBounceVertical = YES;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
//    _scrollView.autoresizesSubviews = NO;

    self.customization = [[Customization alloc] init];

    self.modelView = [[CustomModelView alloc] init];
    _modelView.model = self.customization;
    [self.view addSubview:_modelView];

    self.switchView = [[CustomSwitchView alloc] init];
    _switchView.selectedIndex = 0;
    [self.view addSubview:_switchView];

    self.currentType = CustomSubviewControllerTypeStyle;
    [self addVc:self.styleVC];
    [self addNextVc:self.designVC];

    @weakify(self)
    self.switchView.switchBlock = ^(NSInteger last, NSInteger index) {
        @strongify(self)
        [self handleSwitchIndex:last index:index];
//        DeliveryInfoViewController *vc = [DeliveryInfoViewController new];
//        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//        vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//        [self.tabBarController presentViewController:vc animated:YES completion:nil];
    };

    NSInteger index = [self.customization.models indexOfObject: self.customization.selectedModel];
    if (index != NSNotFound) {
        self.modelView.switchView.index = index;
    }

    self.modelView.switchView.switchBlock = ^(CustomizationModel *model) {
        @strongify(self)
        self.customization.selectedModel = model;
    };


    //    [[RACObserve(_switchView, selectedIndex) distinctUntilChanged] subscribeNext:^(NSNumber *index) {
    //
    //        //切换到第几个的时候   预先加载下一个
    //        //        CustomSubviewControllerType type = index.integerValue;
    //
    //        //初始化  加载第一个  和  第二个
    //        //滑动到下一个结束 1.第一个移除  第二个移到第一个位置 修改offset为0
    //        //              2.如果有下一个  且 下一个可用   加载第二个
    //        //点击按钮  1. 下面的  移除原有的第二个vc  将对应的加载到第二个位置
    //        //        2. 上面的  将对应的vc移动到第一个位置 原有的第一成为二, 第二成为3 修改offset到1的位置
    //    }];
}



- (void)switchToNext {
    self.currentType = self.currentType + 1;
    self.isScrollToNext = YES;
    [self.scrollView setContentOffset:CGPointMake(0, kViewH) animated:YES];
}

- (void)switchToBiggerIndex: (NSInteger)targetIndex lastIndex: (NSInteger)lastIndex{

    self.isScrollToNext = YES;
    self.currentType = targetIndex;

    //跨度多余1 移除原有的第二个
    NSInteger originalTargetIndex = lastIndex + 1;
    [[self vcWithType:originalTargetIndex].view removeFromSuperview];

    //添加新的
    CustomBaseSubViewController *vc = [self vcWithType:targetIndex];
    [self addChildViewController:vc];
    vc.view.frame = CGRectMake(0, kViewH, self.view.width, kViewH);
    [self.scrollView addSubview:vc.view];

    //滚动到下一页
    [self.scrollView setContentOffset:CGPointMake(0, kViewH) animated:YES];
}

- (void)switchToPrevious {
    //5-4 修改contentsize 然后添加4   直接移动即可  不需要移除
    _isScrollToPrevious = YES;

    //将正在显示的移动一个位置, 并修改偏移量
    UIViewController *lastVc = [self vcWithType:_currentType];
    lastVc.view.frame = CGRectMake(0, kViewH, self.view.width, kViewH);
    [_scrollView setContentOffset:CGPointMake(0, kViewH) animated:NO];

    if (_currentType == CustomSubviewControllerTypeOrderInfo) {
//        _scrollView.contentSize = CGSizeMake(0, kViewH * 2);
    } else {
        UIViewController *lastNextVc = [self vcWithType:_currentType + 1];
        [lastNextVc.view removeFromSuperview];
    }
    self.currentType = _currentType - 1;

    //要添加的上一个
    CustomBaseSubViewController *vc = [self vcWithType:_currentType];
    [self addChildViewController:vc];
    vc.view.frame = self.scrollView.frame;
    [self.scrollView addSubview:vc.view];

    //移动
    [self.scrollView setContentOffset:CGPointZero animated:YES];
//    for (UIView *sub in self.scrollView.subviews) {
//        if ([sub.nextResponder isKindOfClass:[UIViewController class]]) {
//            NSAssert(false, [NSString stringWithFormat:@"%@", sub]);
//        }
//    }
}


- (void)switchToSmallerIndex: (NSInteger)targetIndex lastIndex: (NSInteger)lastIndex{
    _isScrollToPrevious = YES;

    //将正在显示的移动一个位置, 并修改偏移量
    UIViewController *lastVc = [self vcWithType:_currentType];
    lastVc.view.frame = CGRectMake(0, kViewH, self.view.width, kViewH);
    [_scrollView setContentOffset:CGPointMake(0, kViewH) animated:NO];

    if (_currentType == CustomSubviewControllerTypeOrderInfo) {
//        _scrollView.contentSize = CGSizeMake(0, kViewH * 2);
    } else {
        UIViewController *lastNextVc = [self vcWithType:_currentType + 1];
        [lastNextVc.view removeFromSuperview];
    }
    self.currentType = targetIndex;

    CustomBaseSubViewController *vc = [self vcWithType:_currentType];
    [self addChildViewController:vc];
    vc.view.frame = self.scrollView.frame;
    [self.scrollView addSubview:vc.view];

    //移动
    [self.scrollView setContentOffset:CGPointZero animated:YES];
}

- (void)handleSwitchIndex: (NSInteger)last index: (NSInteger)index {
    NSAssert(index != last, @"需要添加的vc错误");
    if (index == last + 1) {
        [self switchToNext];
    } else if (index > last + 1) {
        [self switchToBiggerIndex:index lastIndex:last];
    } else if (index == last - 1){
        [self switchToPrevious];
    } else if (index < last - 1) {
        [self switchToSmallerIndex:index lastIndex:last];
    }
}

//添加第一个vc
- (void)addVc: (CustomBaseSubViewController *)vc {
    [self addChildViewController:vc];
    [self.scrollView addSubview:vc.view];
    vc.view.frame = _scrollView.frame;
}

//添加下一个vc
- (void)addNextVc: (CustomBaseSubViewController *)vc {
    NSInteger type = vc.type;
    if (type - _currentType != 1) {
        NSAssert(false, @"添加的VC错误");
        return;
    }
    for (UIView *view in _scrollView.subviews) {
        if ([view.nextResponder isEqual:vc]) {
            return;
        }
        if (view.y == kViewH) {
            [view removeFromSuperview];
            break;
        }
    }
    [self addChildViewController:vc];
    [self.scrollView addSubview:vc.view];
    vc.view.frame = CGRectMake(0, kViewH, self.view.width, kViewH);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //开始滚动的时候
    //如果是5  添加到5上
    //如果是3 - 4

    if (scrollView.contentOffset.y <= 0) {
        return;
    }
    if (!scrollView.isDragging) {
        return;
    }
    if (_currentType == CustomSubviewControllerTypeDepthDesign) {
        if (![_modelView.superview isEqual:[self vcWithType:_currentType].leftView]) {
            [self resetModelViewConstrintsWithSuperView:[self vcWithType:_currentType].leftView];
        }
    } else if (_currentType == CustomSubviewControllerTypeMeasure) {
        if (![_modelView.superview isEqual:[self vcWithType:CustomSubviewControllerTypeOrderInfo].leftView]) {
            [self resetModelViewConstrintsWithSuperView:[self vcWithType:CustomSubviewControllerTypeOrderInfo].leftView];
        }
    } else {
        if (![_modelView.superview isEqual:self.view]) {
            [self resetModelViewConstrintsWithSuperView:self.view];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    if (scrollView.contentOffset.y != scrollView.height) {
        return;
    }
    //第一个vc
    CustomBaseSubViewController *lastVc = [self vcWithType:_currentType];

    self.currentType = _currentType + 1;
    [_switchView setSelectedIndex:_currentType];

    //当前的vc
    CustomBaseSubViewController *currentVc = [self vcWithType:_currentType];

    //移除第一个vc
    [lastVc.view removeFromSuperview];

    //将第二个放到第一个的位置
    currentVc.view.frame = _scrollView.frame;
    [scrollView setContentOffset:CGPointZero animated:NO];

    NSInteger nextType = _currentType + 1;
    //如果下一个可用了  添加下一个vc
    if (nextType > CustomSubviewControllerTypeOrderInfo) {
//        _scrollView.contentSize = _scrollView.bounds.size;
        return;
    }
    CustomBaseSubViewController *nextVc = [self vcWithType:nextType];

    if (!currentVc.canScrollToNext) {
        return;
    }
    [self addNextVc: nextVc];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

    if (scrollView.contentOffset.y != scrollView.height && scrollView.contentOffset.y != 0) {
        return;
    }
    if (_isScrollToNext) {
        self.isScrollToNext = NO;
        //当前的vc
        CustomBaseSubViewController *currentVc = [self vcWithType:_currentType];

        //移除前一个 //
        [self.childViewControllers enumerateObjectsUsingBlock:^(UIViewController *vc, NSUInteger idx, BOOL *stop) {
            if ([vc.view.superview isEqual:self.scrollView] && ![vc isEqual:currentVc]) {
                [vc.view removeFromSuperview];
                *stop = YES;
            }
        }];

        //将新的放到第一个的位置
        currentVc.view.frame = _scrollView.frame;
        [scrollView setContentOffset:CGPointZero animated:NO];

        NSInteger nextType = _currentType + 1;
        //如果下一个可用了  添加下一个vc
        if (nextType > CustomSubviewControllerTypeOrderInfo) {
//            _scrollView.contentSize = _scrollView.bounds.size;
            return;
        }
        CustomBaseSubViewController *nextVc = [self vcWithType:nextType];

        if (!currentVc.canScrollToNext) {
            return;
        }
        [self addNextVc: nextVc];

    } else if (_isScrollToPrevious) {
        self.isScrollToPrevious = NO;
        //当前的vc
        CustomBaseSubViewController *currentVc = [self vcWithType:_currentType];
        if (!currentVc.canScrollToNext) {
            return;
        }
        NSInteger nextType = _currentType + 1;
        CustomBaseSubViewController *nextVc = [self vcWithType:nextType];
        //如果是4-3 减1个的跨度  则不会需要调用
        //否则 需要移除原来的  加入新的
        [self addNextVc: nextVc];
    }
}

// 3 - 4  添加到3 上
// 4 - 5  添加到5上
// 5 - 4  添加到5上
// 5 - 3  添加到super
// 3 - 5  添加到super

//任意index到  4 添加到任意上
// 4 到 任意   添加到任意上

//其他任意到任意   添加到super上
- (void)setCurrentType:(CustomSubviewControllerType)currentType {
    if (currentType == CustomSubviewControllerTypeMeasure) {
        [self resetModelViewConstrintsWithSuperView:[self vcWithType:_currentType].leftView];
    } else if (_currentType == CustomSubviewControllerTypeMeasure){
        [self resetModelViewConstrintsWithSuperView:[self vcWithType:currentType].leftView];
    } else {
        [self resetModelViewConstrintsWithSuperView:self.view];
    }
    _currentType = currentType;
    if (currentType == CustomSubviewControllerTypeOrderInfo) {
        _scrollView.contentSize = CGSizeMake(0, kViewH);
    } else {
        _scrollView.contentSize = CGSizeMake(0, kViewH * 2);
    }
}

- (void)resetModelViewConstrintsWithSuperView: (UIView *)superView {

    [superView addSubview:_modelView];
    [self.view bringSubviewToFront:_switchView];

    CGFloat topOffset;
    CGFloat bottomOffset;
    if ([superView isEqual:self.view]) {
//        topOffset = 64;
//        bottomOffset = 49;
        topOffset = 0;
        bottomOffset = 0;
    } else {
        topOffset = 0;
        bottomOffset = 0;
    }
    [_modelView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView).offset(topOffset);
        layoutViews(^{ //横屏
            make.bottom.equalTo(superView).offset(-bottomOffset);
            make.left.equalTo(superView);
            make.width.equalTo(@(kCustomLandscapeLeftWidth));
        }, ^{ //竖屏
            make.right.left.equalTo(superView);
            make.height.equalTo(@(kCustomPortraitTopHeight));
        });
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _scrollView.frame = self.view.bounds;
    for (UIViewController *vc in self.childViewControllers) {
        if (vc.view.superview ) { //&& vc.view.size != CGSizeMake(self.view.width, kViewH)
            vc.view.size = CGSizeMake(self.view.width, kViewH);
        }
    }
//    if (self.designVC.view.superview && self.designVC.view.width != self.view.width) {
//        self.designVC.view.frame = CGRectMake(0, kViewH, self.view.width, kViewH);
//    }
    [_switchView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(kSwitchViewWidth));
        make.height.equalTo(@(kSwitchViewHeight));
        make.left.equalTo(self.view).offset(30);
        layoutViews(^{ //横屏
            make.centerY.equalTo(self.view).offset(64 - 49);
        }, ^{ //竖屏
            make.centerY.equalTo(self.view).multipliedBy(0.6).offset((64 - 49) / 2);
        });
    }];

    [self resetModelViewConstrintsWithSuperView:_modelView.superview];
}

- (CustomBaseSubViewController *)vcWithType: (CustomSubviewControllerType)type {
    switch (type) {
        case CustomSubviewControllerTypeDepthDesign:
            return self.depathDesignVC;
        case CustomSubviewControllerTypeDesign:
            return self.designVC;
        case CustomSubviewControllerTypeOrderInfo:
            return self.infoVC;
        case CustomSubviewControllerTypeMeasure:
            if (_amountVc) {
                return _amountVc;
            }
            return self.measureVC;
        case CustomSubviewControllerTypeStyle:
            return self.styleVC;
        default: return nil;
    }
}

#pragma mark - Getter And Setter
- (CustomSecondViewController *)designVC {
    if (!_designVC) {
        _designVC = [[CustomSecondViewController alloc] init];
        _designVC.customization = _customization;
        _designVC.target = CustomSubviewControllerTypeDepthDesign;
        _designVC.type = CustomSubviewControllerTypeDesign;
        //绑定到深度设计按钮可用上
        [RACObserve(_designVC, canScrollToNext) subscribeNext:^(NSNumber *x) {
            BOOL enabled = YES;//x.boolValue;
            [self.switchView setEnabled:enabled index:CustomSubviewControllerTypeDepthDesign];
        }];
    }
    return _designVC;
}

- (CustomSecondViewController *)depathDesignVC {
    if (!_depathDesignVC) {
        _depathDesignVC = [[CustomSecondViewController alloc] init];
        _depathDesignVC.type = CustomSubviewControllerTypeDepthDesign;
        _depathDesignVC.target = CustomSubviewControllerTypeMeasure;
        _depathDesignVC.customization = _customization;
        _depathDesignVC.isDepth = YES;

        //绑定到订单信息按钮可用上
        [RACObserve(_depathDesignVC, canScrollToNext) subscribeNext:^(NSNumber *x) {
            BOOL enabled = x.boolValue;
            [self.switchView setEnabled:enabled index:CustomSubviewControllerTypeMeasure];
        }];
    }
    return _depathDesignVC;
}


- (CustomStyleViewController *)styleVC {
    if (!_styleVC) {
        _styleVC = [[CustomStyleViewController alloc] init];
        _styleVC.type = CustomSubviewControllerTypeStyle;
        _styleVC.target = CustomSubviewControllerTypeDesign;
        _styleVC.customization = _customization;
        //绑定到设计按钮可用上
        [RACObserve(_styleVC, canScrollToNext) subscribeNext:^(NSNumber *x) {
            BOOL enabled = YES;//x.boolValue;
            [self.switchView setEnabled:enabled index:CustomSubviewControllerTypeDesign];
        }];
    }
    return _styleVC;
}

- (CustomOrderInfoViewController *)infoVC {
    if (!_infoVC) {
        _infoVC = [[CustomOrderInfoViewController alloc] init];
        _infoVC.type = CustomSubviewControllerTypeOrderInfo;
        _infoVC.customization = _customization;
    }
    return _infoVC;
}

- (CustomNewsViewController *)measureVC {
    if (!_measureVC) {
        _measureVC = [[CustomNewsViewController alloc] init];
        _measureVC.type = CustomSubviewControllerTypeMeasure;
        @weakify(self)
        _measureVC.transitionCompletionAction = ^(CustomNewsAmountViewController *amountVc) {
            @strongify(self)
            amountVc.type = CustomSubviewControllerTypeMeasure;
            amountVc.target = CustomSubviewControllerTypeOrderInfo;
            self.amountVc = amountVc;
        };
        _measureVC.target = CustomSubviewControllerTypeOrderInfo;
        _measureVC.customization = _customization;
        //绑定到设计按钮可用上
        [RACObserve(_measureVC, canScrollToNext) subscribeNext:^(NSNumber *x) {
            BOOL enabled = x.boolValue;
            [self.switchView setEnabled:enabled index:CustomSubviewControllerTypeOrderInfo];
        }];
    }
    return _measureVC;
}

@end
